package org.smile.validate;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import org.smile.beans.BeanProperties;
import org.smile.beans.converter.BeanException;
import org.smile.commons.SmileRunException;
import org.smile.util.StringUtils;

public class ValidateElement {
	/**是否是单个验证不通过返回*/
	private boolean single=ValidateConstants.single;
	
	protected BeanProperties properties=BeanProperties.NORMAL;
	/**验证规则*/
	private Set<Rule> rules=new LinkedHashSet<>();
	/**明细的验证*/
	private Map<String,Set<Rule>> detailRules=new HashMap<>();
	/**当前对象就是集合时使用做为key*/
	static final String CURRENT_DETAILS="_current_";
	/**当前对象就是集合时判断*/
	static final String CURRENT_COLLECTION_FIELD_FLAG="*.";
	/**属性字段是集合时判断*/
	static final String COLLECTION_FIELD_FLAG=".*.";
	
	public ValidateElement(Collection<Rule> rules){
		for(Rule r:rules){
			this.addRule(r);
		}
	}

	public void join(Collection<Rule> join){
		for(Rule r:join){
			this.addRule(r);
		}
	}


	private void addRule(Rule rule){
		if(rule.getFieldName().startsWith(CURRENT_COLLECTION_FIELD_FLAG)){
			rule.setFieldName(rule.getFieldName().substring(CURRENT_COLLECTION_FIELD_FLAG.length()));
			putDetailRules(CURRENT_DETAILS,rule);
		}else {
			int index=rule.getFieldName().indexOf(COLLECTION_FIELD_FLAG);
			if ( index> 0) {
				String collectionField=StringUtils.substring(rule.getFieldName(),0,index);
				rule.setFieldName(rule.getFieldName().substring(index+COLLECTION_FIELD_FLAG.length()));
				this.putDetailRules(collectionField, rule);
			} else {
				this.rules.add(rule);
			}
		}
	}

	private void putDetailRules(String field,Rule rule){
		Set<Rule> ruleSet=this.detailRules.get(field);
		if(ruleSet==null) {
			ruleSet = new HashSet<>();
			this.detailRules.put(field,ruleSet);
		}
		rules.add(rule);
	}
	
	public boolean validate(ValidateSupport action){
		//记录验证的结果
		boolean result=true;
		for(Rule f:rules){
			IValidator validator;
			if(f.getCustom()!=null&&f.getCustom()!=NULLValidater.class){
				//如果有自定义验证类，初始化实例
				try {
					validator=f.getCustom().newInstance().getValidater();
				} catch (Exception e) {
					throw new SmileRunException("自定义验证实例化出错",e);
				}
			}else{
				validator=f.getType().getValidater();
			} 
			try {
				if(!validator.validate(f, action, properties)){
					if(single){
						//单个验证时立即结束验证
						return false;
					}else{
						result=false;
					}
				}
			} catch (BeanException e) {
				throw new SmileRunException(e);
			}
		}
		return result;
	}

	/**是否单个验证*/
	public boolean isSingle() {
		return single;
	}

	public void setSingle(boolean single) {
		this.single = single;
	}
	
}
